/*
 * Exporter.java
 * 
 * This class exports data from a database.
 * 
 * Copyright 2013 Santi Ruiz Andrés <starfly1570@gmail.com>
 * 
 * This file is part of Drawer of Marks.
 * 
 * Drawer of Marks is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Drawer of Marks is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Drawer of Marks.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package blogspot.santiruizpro.drawerofmarks.model;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author starfly1570
 */
public class Exporter {
	
	/**
	 * Exports whole database into a file.
	 * 
	 * @param database the database
	 * @param exportFile the target file
	 */
	public void exportDataBase(DBAccess database, File exportFile) {
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(exportFile));
			exportTable(bw,database.query("Select * from subjects"));
			exportTable(bw,database.query("Select * from divisions"));
			exportTable(bw,database.query("Select * from exams"));
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Exports a single table.
	 * 
	 * @param bw the file buffered writer
	 * @param rows the table
	 */
	private void exportTable(BufferedWriter bw, ArrayList<ArrayList<String>> rows) {
		for ( int i = 0; i < rows.size(); i++ ) {
			ArrayList<String> row = rows.get(i);
			String result = "";
			for ( int j = 0; j < row.size(); j++ ) {
				result += ":" + row.get(j);
			}
			result = result.substring(1) + "\n";
			try {
				bw.write(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			bw.write("END-TABLE\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
